package com.ruiyou.ub;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.webkit.DownloadListener;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import android.widget.Toast;

import java.io.File;

public class UDownloadUtil implements DownloadListener {
    Context context;

    public UDownloadUtil(Context context) {
        this.context = context;
    }

    @Override
    public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
        String fineName = URLUtil.guessFileName(url, contentDisposition, mimetype);
        showDownloadDialog(url, fineName, getLengthString(contentLength));
    }

    @SuppressLint("DefaultLocale")
    String getLengthString(long len) {
        float div; //divisor
        if ((div = 1024 * 1024 * 1024) < len) {
            return String.format("%1.2f GB", len / div);
        } else if ((div = 1024 * 1024) < len) {
            return String.format("%1.2f MB", len / div);
        } else if ((div = 1024) < len) {
            return String.format("%1.2f KB", len / div);
        }
        return len + " B";
    }

    private void downloadFile(String strUrl, File destFile) {
        Uri uri = Uri.parse(strUrl);
        DownloadManager.Request req = new DownloadManager.Request(uri);
        req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        req.setDestinationUri(Uri.fromFile(destFile));
        DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        if (dm != null) {
            dm.enqueue(req);
        } else {
            Toast.makeText(context, "Error: DownLoadManager.Request", Toast.LENGTH_SHORT).show();
        }
    }

    public void downloadPicture(String strUrl) {
        String fileName = URLUtil.guessFileName(strUrl, null,
                MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                        strUrl.substring(strUrl.lastIndexOf('.') + 1)));
        showDownloadDialog(strUrl, fileName, null);
    }

    /**
     * 下载对话框
     *
     * @param strUrl    url
     * @param fileName  目标文件名
     * @param strLength 长度字符串
     */
    private void showDownloadDialog(
            final String strUrl,
            final String fileName,
            String strLength
    ) {
        String dir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS
        ).getAbsolutePath();
        if (strLength == null) strLength = "";
        Util.Callback callback = result -> {
            File dest = result.isEmpty() ? new File(dir, fileName)
                    : new File(dir, result);
            try {
                downloadFile(strUrl, dest);
            } catch (Exception e) {
                Util.showDialog(
                        context,
                        context.getString(R.string.warning),
                        e.getMessage(),
                        DialogType.INFO,
                        null
                );
            }
        };
        Util.showDialog(
                context,
                context.getString(R.string.start_download),
                context.getString(
                        R.string.download_message,
                        dir + File.separator + fileName, strLength
                ),
                DialogType.EDIT,
                callback
        );
    }
}
